package org.kfive.nova.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by admin on 2017-04-09.
 */
public class ConcurrentCounter {

    private AtomicInteger counter;

    public ConcurrentCounter(Integer counter){
        this.counter = new AtomicInteger(counter);
    }

    public Integer increment(){
        return this.counter.incrementAndGet();
    }

    public Integer getCounter(){
        return this.counter.get();
    }

    public static void main(String[] args) {
        final ConcurrentCounter counter = new ConcurrentCounter(0);
        Thread addThread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i =0;i<1000;i++){
                    counter.increment();
                }
            }
        });
        Thread addThread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i =0;i<1000;i++) {
                    counter.increment();
                }
            }
        });
        addThread1.start();
        addThread2.start();
        try {
            addThread1.join();
            addThread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("count="+counter.getCounter());
    }
}
